package com.huawei.mytestapp.slice;

import com.danikula.videocache.CacheListener;
import com.danikula.videocache.HttpProxyCacheServer;
import com.huawei.mytestapp.ResourceTable;
import com.wang.avi.indicators.BallSpinFadeLoaderIndicator;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.Revocable;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.common.Source;
import ohos.media.player.Player;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PlayingSlice extends AbilitySlice implements SurfaceOps.Callback {
    public static final String URL = "https://1251316161.vod2.myqcloud.com/5f6ddb64vodsh1251316161/6950eead5285890812637029535/iUn2HnRCGxMA.mp4";
    private Player player=new Player(this);
    int p=0;
    public static HttpProxyCacheServer mCacheServerProxy = null;
    SurfaceProvider surfaceProvider;
    private Slider slider;
    public static int percents = 0,x=1,playing=1;
    public EventHandler handler = new EventHandler(EventRunner.create(true));
    Revocable revocable;
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);

        //设置xml
        setUIContent(ResourceTable.Layout_playing);
        //设置聊天框内容

        ///data/uesr/0/com.huawei.mytestapp/cache/video-cache/1692480a32ab5f2f396e1c900d7eb4e8.mp4.download
        ///data/user/0/com.huawei.mytestapp/cache/video-cache/1692480a32ab5f2f396e1c900d7eb4e8.mp4.download
        if(p==0) {
            String cacheDirPath = "/data/user/0/" + this.getBundleName() + "/cache/";
            File appCacheDir = new File(cacheDirPath, "video-cache/1692480a32ab5f2f396e1c900d7eb4e8.mp4.download");
            HiLog.info(new HiLogLabel(3, 0, "cache"), "ff2222:" + appCacheDir.getPath());
            if (appCacheDir != null) appCacheDir.delete();
            p=1;
        }
        //初始化播放器
//        player =
        //播放
        Context con=this;
        //设置surfaceProvider
        SurfaceOps.Callback callback=this;

        //设置滚动条
        slider = (Slider) findComponentById(ResourceTable.Id_slider);
        slider.setDividerLineColor(new Color(Color.rgb(13, 245, 123)));
        slider.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b) {
                if (b && i < percents-1) player.rewindTo(player.getDuration() * (i-2) * 10);
            }

            @Override
            public void onTouchStart(Slider slider) {
            }

            @Override
            public void onTouchEnd(Slider slider) {
            }
        });
        int time=801000;
        int o=time/100;



        surfaceProvider =(SurfaceProvider) findComponentById(ResourceTable.Id_surfaceprovider);
        surfaceProvider.getSurfaceOps().get().addCallback(callback);
        surfaceProvider.pinToZTop(true);


        if (mCacheServerProxy == null) mCacheServerProxy = new HttpProxyCacheServer(con);



        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            revocable =globalTaskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {

                mCacheServerProxy.registerCacheListener(new CacheListener() {
                    @Override
                    public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
                        percents =percentsAvailable;
                        HiLog.info(new HiLogLabel(3,0,"cache"),"ff:"+cacheFile.getPath());
                        if (percentsAvailable == 99) {
                            mCacheServerProxy.shutdown();
                            mCacheServerProxy.unregisterCacheListener(this);
                        }
                    }
                }, URL);
                player.setSource(new Source(mCacheServerProxy.getProxyUrl(URL)));
                player.prepare();
                player.play();

            }
            });


//        ScrollView s=(ScrollView)findComponentById(ResourceTable.Id_scrollview);
//        //directionalLayout2，其中包括一个ScrollView和一个加载动画BallSpinFadeLoaderIndicator
//        DirectionalLayout layout=(DirectionalLayout)findComponentById(ResourceTable.Id_directionlayout2);
        //加载动画
//        BallSpinFadeLoaderIndicator ballSpinFadeLoaderIndicator=new BallSpinFadeLoaderIndicator(this);
//        DirectionalLayout.LayoutConfig ballSpinFadeLoaderIndicatorConfig = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
//        ballSpinFadeLoaderIndicatorConfig.setMargins(430,250,0,0);
//        ballSpinFadeLoaderIndicator.setLayoutConfig(ballSpinFadeLoaderIndicatorConfig);
//        ballSpinFadeLoaderIndicator.setHeight(200);
//        ballSpinFadeLoaderIndicator.setWidth(200);
//        ballSpinFadeLoaderIndicator.setVisibility(Component.HIDE);
//        //将加载动画BallSpinFadeLoaderIndicator添加进directionalLayout2
//        layout.addComponent(ballSpinFadeLoaderIndicator);
//        //动画开始
//        ballSpinFadeLoaderIndicator.start();
//
        BallSpinFadeLoaderIndicator ballSpinFadeLoaderIndicator1=new BallSpinFadeLoaderIndicator(this);
        DirectionalLayout directionalLayout=(DirectionalLayout) findComponentById(ResourceTable.Id_directionlayout_playing);
        directionalLayout.addComponent(ballSpinFadeLoaderIndicator1);
        ballSpinFadeLoaderIndicator1.start();
        Runnable run=new Runnable() {
            @Override
            public void run() {
                getUITaskDispatcher().asyncDispatch(new Runnable(){
                    @Override
                    public void run() {

                        try {
                            if(player.getCurrentTime()>0){
                                directionalLayout.setVisibility(Component.INVISIBLE);
                            HiLog.info(new HiLogLabel(3, 0, "cache"), "iyyyyyyyyyy:" + player.getCurrentTime() / o);
                            slider.setProgressValue(player.getCurrentTime() / o);
                            }
                            slider.setViceProgress(percents);
                            HiLog.info(new HiLogLabel(3,0,"cache"),"ggggggg:"+String.valueOf(percents));
//                            if(player.getCurrentTime() / o>=percents)
//                            {player.pause();
//
//                            }
                            //HiLog.info(new HiLogLabel(3,0,"cache"),"gjjjjj:"+surfaceProvider.isComponentDisplayed()+surfaceProvider.isEnabled()+surfaceProvider.getContentEnable());

                        } finally {

                        }
                    }
                });
                handler.postTask(this, 1000);
            }
        };
        handler.postTask(run, 2000);


        //播放按键
        Image play=(Image)findComponentById(ResourceTable.Id_play);
        Image pause=(Image)findComponentById(ResourceTable.Id_pause);
        play.setVisibility(Component.HIDE);
        findComponentById(ResourceTable.Id_play).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component Component) {
                player.play();
                play.setVisibility(ohos.agp.components.Component.HIDE);
                pause.setVisibility(ohos.agp.components.Component.VISIBLE);
            }
        });
        //暂停按键
        findComponentById(ResourceTable.Id_pause).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component Component) {
                player.pause();
                play.setVisibility(ohos.agp.components.Component.VISIBLE);
                pause.setVisibility(ohos.agp.components.Component.HIDE);
            }
        });
        findComponentById(ResourceTable.Id_tab_back).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                slider.invalidate();
                handler.removeTask(run);
                revocable.revoke();
                player.stop();
//                PlayingSlice.super.terminate();
                Intent secondIntent = new Intent();
                secondIntent.setOperation(new Intent.OperationBuilder()
                        .withBundleName("com.huawei.mytestapp")
                        .withAbilityName("com.huawei.mytestapp.MainAbility")
                        .build());
                startAbility(secondIntent);
            }
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }
    @Override
    public void surfaceCreated(SurfaceOps surfaceOps) {
        player.setSurfaceOps(surfaceProvider.getSurfaceOps().get());
        player.prepare();
        HiLog.info(new HiLogLabel(3,0,"cache"),"setwanle:1111111111111111111111111111");

    }
    @Override
    public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {}
    @Override
    public void surfaceDestroyed(SurfaceOps surfaceOps) {
    }

    @Override
    public void onStop(){
        mCacheServerProxy.shutdown();
        HiLog.info(new HiLogLabel(3,0,"cache"),"stoppppppppppp11111111111");
    }

}

